// import T from 'element/package/Table'
import './index.scss'
import config from '@/config/defaultSetting'
import FormBox from '../Form/FormBox'
import Empty from '../tool/Empty.vue'
import Affix from '../Affix/Affix.vue'
import { tableDom } from '@/core/mixins'

export default {
  name: 'STable',
  components: {
    FormBox,
    Empty,
    Affix
  },
  mixins: [tableDom],
  data () {
    return {
      filterData: {}, // 删选条件

      localTableData: [],
      localSort: null, // 排序条件
      localLoading: false,
      localPagination: Object.assign({}, this.pagination),
      localFeild: Object.assign({}, this.dataFeild),

      tableAttrs: Object.assign({}, {
        'row-key': 'id',
        size: 'small',
        border: true
      }, this.tableProps),

      selectedRows: [],
      selectedRowKeys: [],

      renderFilterFlag: true,
      renderTableFlag: true,
      renderFlag: true
    }
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    dataPops: {
      type: Array,
      default: () => {
        return []
      }
    },
    rowKey: {
      type: [String, Function],
      default: 'key'
    },
    siderSpan: {
      type: Number,
      default: 12
    },
    pageNum: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: config.pageSize
    },
    // 请求i地址
    reqUrl: {
      type: String,
      default: ''
    },
    // 分页键值对
    dataFeild: {
      type: Object,
      default: () => {
        return {
          data: 'data',
          total: 'total',
          pageNum: 'page'
        }
      }
    },
    tableProps: {
      type: Object,
      default: () => {
        return {}
      }
    },
    alert: {
      type: [Object, Boolean],
      default: null
    },
    column: {
      type: Array,
      default: () => []
    },
    filterProps: {
      type: Object,
      default: () => null
    },
    showSizeChanger: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'default'
    },
    dataKey: {
      type: String,
      default: 'data'
    },
    tableId: {
      type: String,
      default: 'tableInnerWrapper'
    },
    pagination: {
      type: Object,
      default: () => {
        return {}
      }
    },
    loading: {
      type: Boolean,
      default: false
    },
    queryFn: {
      type: Function,
      default: null
    },
    callback: {
      type: Function,
      default: null
    },
    queryPropsParams: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    pageNum (val) {
      Object.assign(this.localPagination, {
        'current-page': val
      })
    },
    pageSize (val) {
      Object.assign(this.localPagination, {
        pageSize: val
      })
    },
    showSizeChanger (val) {
      Object.assign(this.localPagination, {
        showSizeChanger: val
      })
    },
    // queryPropsParams (val) {
    //   this.refresh(true)
    // },
    filterProps: {
      handler (val) {
        if (val && val.watch) {
          const items = val.items
          const filterData = {}
          items.map(x => {
            if (x.initialValue != null) {
              filterData[x.key] = x.initialValue
            }
          })
          this.filterData = { ...filterData }
        }
      }
    }
  },
  created () {
    if (this.filterProps) {
      const items = this.filterProps.items
      const filterData = {}
      items.map(x => {
        if (x.initialValue != null) {
          filterData[x.key] = x.initialValue
        }
      })
      this.filterData = { ...filterData }
    }
    this.localFeild = Object.assign({}, this.localFeild, this.dataFeild)
    if (this.queryFn) {
      // 判断自主加载数据
      const { pageNo } = this.$route.params
      const localPageNum = (pageNo && parseInt(pageNo)) || this.pageNum
      this.localPagination = this.pagination ? Object.assign({}, this.localPagination, {
        'current-page': localPageNum,
        // 'hide-on-single-page': true,
        pageSize: this.pageSize
      }) : false
      this.loadData()
    } else {
      this.localTableData = this.dataPops
    }
  },
  methods: {
    /**
     * 表格重新加载方法
     * 如果参数为 true, 则强制刷新到第一页
     * @param Boolean bool
     */
    refresh (bool = false) {
      bool && (this.localPagination = Object.assign({}, {
        'current-page': 1,
        pageSize: this.localPagination.pageSize || this.pageSize
      }))
      this.loadData()
    },
    // 重新加载表格
    reloadTable () {
      const that = this
      this.renderTableFlag = false
      this.refresh(true)
      this.$nextTick(function () {
        that.renderTableFlag = true
      })
    },
    // 重新加载删选表单
    reloadFilter () {
      this.renderFilterFlag = false
      this.refresh(true)
      this.$nextTick(function () {
        this.renderFilterFlag = true
      })
    },
    curPaginationChange (val) {
      this.loadData({ pageNum: val })
    },
    // 每页条数改变
    curPaginationSizeChange (val) {
      this.localPagination.pageSize = val
      this.loadData({ pageSize: val })
    },
    rowClick (row) {
      this.$emit('rowClick', row)
    },
    selectChange (val) {
      this.$emit('selectionChange', val)
    },
    sortChange (e) {
      let values = {}
      if (e.order) {
        values = {
          orderField: e.prop,
          orderType: e.order === 'ascending' ? 'asc' : 'desc'
        }
        this.localSort = values
      }
      this.loadData()
    },
    // 当用户对某一行展开或者关闭的时候会触发该事件
    expandChange (row, expandedRows) {
      const { tableAttrs } = this
      if (Array.isArray(expandedRows)) {
        try {
          const keys = expandedRows.map(x => { return x[tableAttrs['row-key']] })
          // 判断展开或关闭
          if (keys.includes(row[tableAttrs['row-key']])) {
            this.$emit('expandRow', row)
          }
        } catch (err) {
          console.log(err)
        }
      }
    },
    searchSubmit (e) {
      if (this.queryFn) {
        console.log(e)
        this.filterData = { ...e }
        this.loadData({ ...this.localPagination, pageNum: 1 })
      } else {
        this.$emit('filterHandle', e)
      }
    },
    reload () {
      this.renderFlag = false
      this.filterData = null
      this.localSort = null
      this.refresh(true)
      this.$nextTick(function () {
        this.renderFlag = true
      })
    },
    /**
    * 加载数据方法
    * @param {Object} pagination 分页选项器
    */
    loadData (pagination) {
      this.localLoading = true
      // 合并axios参数，包括页码，页数，排序，过滤和筛选表单值
      const parameter = Object.assign({}, {
        ...this.queryPropsParams,
        ...this.filterData
      })
      const headers = Object.assign({
        pageNum: (pagination && pagination.pageNum) || this.localPagination['current-page'],
        pageSize: (pagination && pagination.pageSize) || this.localPagination.pageSize
      }, {
        ...this.localSort
      })
      this.queryFn(headers, parameter).then(res => {
        this.localPagination = Object.assign({}, this.localPagination, {
          total: (res.recordCounts && typeof res.recordCounts === 'number') ? res.recordCounts : 0,
          'current-page': res.pageNum ? parseInt(res.pageNum) : 1,
          pageSize: headers.pageSize
        })
        this.localTableData = res && Array.isArray(res) ? res : res[this.dataKey] || []
        if (this.callback) this.callback(res)
      }).finally(() => {
        this.localLoading = false
      })
    }
  },
  render (h) {
    const { localPagination, localTableData, localLoading, renderFilterFlag, renderTableFlag, renderFlag, tableAttrs } = this
    const { column, pagination, queryFn, dataPops, filterProps, loading, siderSpan, title, rowKey, tableId } = this.$props
    const $scopedSlots = this.$scopedSlots

    const table = (
      <div>
        <el-table
          class="borderTable"
          v-loading={queryFn ? localLoading : loading}
          element-loading-text="加载中."
          element-loading-background="rgba(255, 255, 255, 0.7)"
          element-loading-customClass="v-loading"
          element-loading-spinner="iconfont icon-weibiaoti-3"
          // cell-style={{padding: '6px 0'}}
          size={tableAttrs.size}
          border={tableAttrs.border}
          ref="table"
          rowKey={rowKey}
          tree-props={{ children: 'children', hasChildren: 'hasChildren' }}
          data={queryFn ? localTableData : dataPops}
          {...{ props: tableAttrs, scopedSlots: { ...this.$scopedSlots } }}
          onSelection-change={this.selectChange}
          onSort-change={this.sortChange}
          onRow-click={this.rowClick}
          onExpand-change={this.expandChange}
        >
          <empty slot="empty"></empty>
          {tableAttrs.selection &&
            <el-table-column type="selection" width="40px" fixed="left" selectable={tableAttrs.selectable}></el-table-column>
          }
          {column.map(item => {
            return h('el-table-column', {
              props: {
                prop: item.prop,
                label: item.label,
                width: item.width ? item.width : item.prop === 'sort' ? '64' : 'auto',
                'show-overflow-tooltip': true,
                // 'header-align': 'center',
                align: item.prop === 'sort' ? 'center' : item.align || 'auto',
                fixed: item.prop === 'sort' ? 'left' : item.prop === 'action' ? 'right' : false,
                ...item.rest
              },
              scopedSlots: {
                default: scope => {
                  const value = scope.row[item.prop]
                  if ($scopedSlots[item.prop]) {
                    return h('span', {
                      // slot: 'date',
                    }, $scopedSlots[item.prop](value, scope.row, scope.$index))
                  } else if (item.prop === 'sort') {
                    return h('span', {}, scope.$index + 1)
                  } else {
                    return h('span', {}, value || value === 0 ? value : '--')
                  }
                }
              }
            })
          })}
        </el-table>
        {pagination &&
          <affix style="background: #fff">
            <el-pagination
              class="mt16 tr"
              hide-on-single-page={!queryFn}
              background
              // pager-count={6}
              page-size={localPagination.pageSize}
              {...{
                props: queryFn ? localPagination : pagination
              }}
              layout={localPagination.layout || 'slot, prev, pager, next, sizes, jumper'}
              onCurrent-change={this.curPaginationChange}
              onSize-change={this.curPaginationSizeChange}
            >
              <span class="fn fl f13 c_regular">
                {queryFn && localTableData.length > 0 &&
                  <span>
                    总共{localPagination.total}条 显示{((localPagination['current-page'] - 1) * this.pageSize) + 1} - {((localPagination['current-page'] - 1) * this.pageSize) + localTableData.length}条
                  </span>
                }
              </span>
            </el-pagination>
          </affix>
        }
      </div>
    )

    return (
      renderFlag && <div class="tableWrapper">
        {filterProps && renderFilterFlag &&
          <el-card class="tableFilter boxCard" bodyStyle={{ paddingTop: title ? 0 : '10px' }}>
            {title && <div slot="header" class="boxHeader">
              <h2>{title + '信息查询'}</h2>
            </div>}
            <form-box layoutCol={{ sm: 12, md: 8, lg: 6 }} {...{ props: filterProps }} isFilter={true} searchHandle={this.searchSubmit}></form-box>
          </el-card>
        }
        <el-card class="tableInnerWrapper boxCard" id={tableId} bodyStyle={{ paddingTop: title ? 0 : '10px' }}>
          {title && <div slot="header" class="boxHeader">
            {title && <h2>{title}</h2>}
            {$scopedSlots['table-operator'] && $scopedSlots['table-operator']()}
          </div>}
          {$scopedSlots['table-switch'] && $scopedSlots['table-switch']()}
          {$scopedSlots.sumBox && $scopedSlots.sumBox()}
          {renderTableFlag && ($scopedSlots['table-right']
            ? <el-row gutter={24}><el-col span={12}><el-card>{table}</el-card></el-col><el-col span={12}>{$scopedSlots['table-right']()}</el-col></el-row>
            : renderTableFlag && ($scopedSlots['table-left']
              ? <el-row gutter={24}><el-col span={siderSpan}>{$scopedSlots['table-left']()}</el-col><el-col span={24 - siderSpan}><el-card>{table}</el-card></el-col></el-row>
              : table
            )
          )}
        </el-card>
      </div>
    )
  }
}
